package weibo;

import java.net.URI;
import java.util.Scanner;

import com.tencent.weibo.api.Statuses_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;
import com.tencent.weibo.utils.WeiBoConst;

public class TencentAPI implements IWeiboAPI {

	private String urlHead = "http://open.t.qq.com/cgi-bin/authorize?oauth_token=";
	private OAuth oauth;
	private OAuthClient client;

	public TencentAPI() {
		oauth = new OAuth();
		client = new OAuthClient();
	}

	@Override
	public void connect() {
		// 获取request token
		try {
			oauth = client.requestToken(oauth);
			if (oauth.getStatus() == 1) {
				System.out.println("Get Request Token failed!");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String oauth_token = oauth.getOauth_token();
		String url = urlHead + oauth_token;
		if (!java.awt.Desktop.isDesktopSupported()) {
			System.err.println("Desktop is not supported (fatal)");
			System.exit(1);
		}
		java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
		if (desktop == null
				|| !desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
			System.err
					.println("Desktop doesn't support the browse action (fatal)");
			System.exit(1);
		}
		try {
			desktop.browse(new URI(url));
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
		verify();
	}

	public void verify() {
		System.out.println("Input your verification code：");
		Scanner in = new Scanner(System.in);
		String verify = in.nextLine();
		// 获取access token
		oauth.setOauth_verifier(verify);
		try {
			oauth = client.accessToken(oauth);

			System.out.println("Response from server：");
			if (oauth.getStatus() == 2) {
				System.out.println("Get Access Token failed!");
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getTimeLine() {
		String pagetime = "0";
		String reqnum = "20";
		String lastid = "0";
		String type = "0";
		String contenttype = "0";
		String accesslevel = "0";
		Statuses_API tStatAPI = new Statuses_API();
		String response = "";
		try {
			response = tStatAPI.mentions_timeline_ids(oauth,
					WeiBoConst.ResultType.ResultType_Json, pagetime, reqnum,
					lastid, type, contenttype, accesslevel)
					+ "\n\r";
			tStatAPI.user_timeline_ids(oauth,
					WeiBoConst.ResultType.ResultType_Xml, "0", pagetime,
					reqnum, lastid, "xuemanzi", type, contenttype, accesslevel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}
}
